<template>
  <div class="container">
    <!-- 搜索栏 -->
    <div class="wrapper search-box">
      <div class="cart-search">
        <i class="el-icon-search"></i>
        <input class="input" v-model="input" type="text" placeholder="请输入内容" />
        <button>搜索</button>
      </div>
    </div>
    <!-- 购物车主体 -->
    <div class="wrapper cart-body">
      <div v-if="loading">加载中...</div>
      <div v-else>
        <!-- 购物车存在商品 -->
        <div class="cart-goods" v-show="!isEmpty">
          <!-- 商品头部 -->
          <div class="goods-header">
            <div>
              <a class="goods-header-item" href="#">
                <i>全部商品</i>
                <span class="goods-num">{{ goods.length }}</span>
              </a>
            </div>
            <!-- 收货地址 -->
            <div class="goods-delivery">
              <i>配送至：</i>
              <input type="text" autocomplete="off" placeholder="江西农业大学"/>
            </div>
          </div>
          <!-- 总览 -->
          <div class="goods-all">
            <div class="check-box">
              <input type="checkbox" :checked="isAllchecked" @change="handleCheckAll" />
              全选
            </div>
            <div class="good">商品</div>
            <div class="price">单价</div>
            <div class="num">数量</div>
            <div class="toDo">操作</div>
          </div>
          <!-- 商品列表 -->
          <div class="goods-list" v-for="(item, index) in goods" :key="item.id">
            <div class="goods">
              <!-- 每个商品的选中状态由 selectId 中是否包含来决定 -->
              <input type="checkbox" :checked="selectId.includes(item.id)" @change="selectFun(item.id)" />
              <img :src="item.imgUrl" alt="" />
              <p class="goods-intro">{{ item.title }}</p>
              <p class="goods-price">￥&nbsp;{{ item.price }}&nbsp;元</p>
              <div class="goods-num">
                <button class="el-icon-minus" @click="decreaseNum(item)"></button>
                <p>{{ item.ordernum }}</p>
                <button class="el-icon-plus" @click="addNum(item)"></button>
              </div>
              <div class="goods-toDo">
                <a href="javascript:;" @click="delectFun(index)">移除</a>
                <a href="javascript:;" @click="payOrder">付款</a>
              </div>
            </div>
          </div>
          <!-- 商品总结 -->
          <div class="goods-end">
            <div class="total-Price">总价为:&nbsp;{{ totalPrice }}&nbsp;元</div>
            <a href="javascript:;" @click="payOrder">付款</a>
          </div>
        </div>
        <!-- 购物车为空 -->
        <div class="cart-empty" v-show="isEmpty">
          <div class="message">
            <ul>
              <li>购物车空空的哦~去看看别的商品吧~</li>
              <li><a href="#">去购物&gt;</a></li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <!-- 推荐 -->
    <div class="wrapper recommend">
      <!-- 随你喜欢 随手购模块 列表 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="猜你喜欢" name="first">
          <el-carousel autoplay :interval="2000" trigger="click" type="card" height="220px">
            <el-carousel-item v-for="(item, idx) in items" :key="idx">
              <div>
                <img :src="item.imgUrl" alt="" />
                <p class="title">{{ item.title }}</p>
                <p class="price">￥&nbsp;{{ item.price }}&nbsp;元</p>
                <a href="javascript:;" @click="addToCart(item)">加入购物车</a>
              </div>
            </el-carousel-item>
          </el-carousel>
        </el-tab-pane>
        <el-tab-pane label="随手购" name="second">
          <el-carousel autoplay :interval="2000" trigger="click" type="card">
            <el-carousel-item v-for="item in items" :key="item.id">
              <div>
                <img :src="item.imgUrl" alt="" />
                <p class="title">{{ item.title }}</p>
                <p class="price">￥&nbsp;{{ item.price }}&nbsp;元</p>
                <a href="#" @click="addToCart(item)">加入购物车</a>
              </div>
            </el-carousel-item>
          </el-carousel></el-tab-pane
        >
      </el-tabs>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      input: '',
      activeIndex: '1',
      isEmpty: false,
      // 存放选中商品 id
      selectId: [],
      // 商品列表
      goods: [],
      // 获取用户名
      username: '',
      // 引入加载
      loading: true, // 新增加载状态
      // 当前活跃项
      activeName: 'first',
      // 推荐列表
      items: [],
    }
  },
  created() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const username = userInfo.username || ''
    fetch('/data/cart.json')
      .then((res) => res.json())
      .then((data) => {
        const userCart = data.find((item) => item.username === username)
        this.goods = userCart && Array.isArray(userCart.goods) ? userCart.goods : []
        this.isEmpty = this.goods.length === 0
        this.loading = false // 数据加载完成
      })
      .catch(() => {
        this.goods = []
        this.isEmpty = true
        this.loading = false
      })
    //
    fetch('/data/goods.json')
      .then((res) => res.json())
      .then((data) => {
        this.items = data
      })
      .catch((err) => {
        this.carouselItems = []
        console.error('获取轮播图数据失败', err)
      })
  },

  // 监听器
  watch: {
    // 对 goods 数组进行操作时每次都会进行判断从而为 isEmpty 赋值
    goods: {
      handler(val) {
        this.isEmpty = val.length === 0
      },
      deep: true,
    },
  },
  // 计算属性 通过计算为属性赋值
  computed: {
    // 全选状态
    isAllchecked() {
      return this.goods.length > 0 && this.selectId.length === this.goods.length
    },
    // 已选列表 返回所有被选中的商品对象数组
    selectList() {
      // 要先确保goods是数组
      return Array.isArray(this.goods) ? this.goods.filter((item) => this.selectId.includes(item.id)) : []
    },
    // 计算总价
    totalPrice() {
      let price = 0
      this.selectList.forEach((item) => {
        price += item.price * item.ordernum
      })
      return price
    },
  },
  methods: {
    // 全选、反选
    handleCheckAll() {
      if (this.selectId.length === this.goods.length) {
        this.selectId = []
      } else {
        this.selectId = this.goods.map((item) => item.id)
      }
    },
    // 单选、多选
    selectFun(id) {
      const idx = this.selectId.indexOf(id)
      if (idx === -1) {
        this.selectId.push(id)
      } else {
        this.selectId.splice(idx, 1)
      }
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    // 删除商品函数
    delectFun(index) {
      // idIndex 表示被删除项在 selectId 中的下标
      let idIndex = this.selectId.indexOf(this.goods[index].id)
      this.goods.splice(index, 1)
      this.selectId.splice(idIndex, 1)
    },
    // 添加商品函数
    addToCart(item) {
      // 确定goods已加载完成
      if (!Array.isArray(this.goods)) {
        this.goods = []
      }
      // 判定此商品是否已加入购物车中
      const flag = this.goods.find((e) => e.id === item.id)
      if (!flag) {
        this.goods.push({
          id: item.id,
          imgUrl: item.imgUrl,
          title: item.title,
          price: item.price,
          ordernum: 1,
        })
        this.selectId.push(item.id)
      } else {
        alert('您的购物车中已有此商品！')
      }
    },
    decreaseNum(item) {
      if (item.ordernum > 0) {
        item.ordernum--
        // 数量为 0 时自动取消勾选
        if (item.ordernum === 0) {
          const idx = this.selectId.indexOf(item.id)
          if (idx !== -1) {
            this.selectId.splice(idx, 1)
          }
        }
      } else {
        item.ordernum = 0
        const idx = this.selectId.indexOf(item.id)
        if (idx !== -1) {
          this.selectId.splice(idx, 1)
        }
      }
    },
    addNum(item) {
      item.ordernum++
      // 只有该商品不存在于选中数组中才选中
      const idx = this.selectId.indexOf(item.id)
      if (idx === -1) {
        this.selectId.push(item.id)
      }
    },
    // 付款（下单）
    payOrder() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      const username = userInfo.username || ''
      if (!username) {
        alert('请先登录！')
        return
      }
      // 只提交已选商品
      const goods = this.selectList
      if (!goods.length) {
        alert('请选择要结算的商品！')
        return
      }
      // 先下单
      fetch('http://localhost:3000/addOrder', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, goods }),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data.status === 200) {
            // 下单成功后，依次删除购物车中已付款商品
            const deletePromises = goods.map((item) =>
              fetch('http://localhost:3000/deleteCartItem', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, id: item.id }),
              })
            )
            Promise.all(deletePromises).then(() => {
              alert('下单成功！')
              // 前端同步移除
              this.goods = this.goods.filter((item) => !this.selectId.includes(item.id))
              this.selectId = []
              this.$router.push('/order')
            })
          } else {
            alert('下单失败：' + data.message)
          }
        })
        .catch(() => {
          alert('下单请求失败！')
        })
    },
  },
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
}

.container {
  width: 100%;
  background-color: #dfe0df;
}

.wrapper {
  width: 1110px;
}

/* 搜索栏 */
.search-box {
  height: 100px;
  margin: auto;
}
.cart-search {
  float: right;
  display: flex;
  width: 316px;
  height: 30px;
  border: 1px solid #ffa500;
  border-radius: 15px;
  justify-content: center;
  align-items: center;
  margin-top: 50px;
}
.cart-search .input {
  display: block;
  height: 99%;
  width: 250px;
  outline: none;
  border: none;
  background-color: #dfe0df;
}

.cart-search button {
  width: 50px;
  height: 30px;
  color: #f6e5df;
  background-color: #ffa500;
  border: none;
  border-radius: 15px;
  cursor: pointer;
}
/* 购物车主体 */
.cart-body {
  margin: auto;
}
/* 购物车存在商品 */
/* 商品头部 */
.cart-body .goods-header {
  display: flex;
  width: 100%;
  height: 40px;
  justify-content: space-between;
}

.cart-body .goods-header .goods-header-item {
  text-decoration: none;
  color: #ffa500;
  padding-left: 5px;
  line-height: 40px;
  font-weight: 700;
}

.cart-body .goods-header .goods-header-item span {
  margin-left: 5px;
}
/* 地址 */
.cart-body .goods-header .goods-delivery {
  line-height: 40px;
  font-size: 15px;
  font-weight: 300;
}

.cart-body .goods-header .goods-delivery input {
  outline: none;
}

/* 总览 */
.cart-body .goods-all {
  display: flex;
  line-height: 40px;
  background-color: #ededed;
}

.cart-body .goods-all .check-box {
  margin-left: 30px;
}

.cart-body .goods-all .good {
  margin-left: 100px;
}

.cart-body .goods-all .price {
  margin-left: 400px;
}

.cart-body .goods-all .num {
  margin-left: 150px;
}

.cart-body .goods-all .toDo {
  margin-left: 150px;
}

/* 商品列表 */
.cart-body .cart-goods .goods-list {
  width: 100%;
  margin: auto;
  background-color: whitesmoke;
}

.cart-body .cart-goods .goods-list .goods {
  display: flex;
  height: 100px;
  border: 1px solid #ffa500;
  border-collapse: collapse;
  margin-top: 10px;
  align-items: center;
}

.cart-body .cart-goods .goods-list .goods input {
  margin-left: 30px;
}

.cart-body .cart-goods .goods-list .goods img {
  width: 70px;
  height: 70px;
  margin-left: 70px;
}
/* 介绍 */
.cart-body .cart-goods .goods-list .goods .goods-intro {
  width: 350px;
  height: 60px;
  margin: 0 0 0 15px;
  font-size: 13px;
  /* 文字换行 */
  word-break: break-all;
  white-space: normal;
  overflow-wrap: break-word;
}
/* 价格 */
.cart-body .cart-goods .goods-list .goods .goods-price {
  width: 100px;
  margin: -40px 0 0 28px;
  text-align: center;
  font-size: 15px;
}
/* 商品中数量模块 */
.cart-body .cart-goods .goods-list .goods .goods-num {
  display: flex;
  width: 90px;
  height: 20px;
  justify-content: space-between;
  margin: -40px 0 0 90px;
  border: 1px solid gray;
}

.cart-body .cart-goods .goods-list .goods .goods-num button {
  width: 20px;
  height: 18px;
  text-align: center;
  background-color: #dfe0df;
  border: none;
  cursor: pointer;
}

.cart-body .cart-goods .goods-list .goods .goods-num p {
  line-height: 20px;
  font-size: 13px;
  font-weight: 300;
}
/* 操作模块 */
.cart-body .cart-goods .goods-list .goods .goods-toDo {
  display: flex;
  width: 40px;
  height: 60px;
  margin: -40px 0 0 119px;
  flex-direction: column;
  justify-content: space-between;
}

.cart-body .cart-goods .goods-list .goods .goods-toDo a:first-child {
  text-decoration: none;
  color: gray;
  font-size: 13px;
  margin-top: 10px;
}

.cart-body .cart-goods .goods-list .goods .goods-toDo a:last-child {
  text-decoration: none;
  color: #ffa500;
}

/* 商品结尾 */
.cart-body .cart-goods .goods-end {
  display: flex;
  height: 60px;
  margin-top: 10px;
  border: 1px solid #ffa854;
  justify-content: flex-end;
  align-items: center;
}

.cart-body .cart-goods .goods-end .total-Price {
  margin-right: 300px;
}

.cart-body .cart-goods .goods-end a {
  width: 50px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  color: whitesmoke;
  border: 1px solid #ffa500;
  border-radius: 25%;
  background-color: #ffa500;
  text-decoration: none;
  margin-right: 90px;
}

/* 购物车为空 */
.cart-body .cart-empty {
  width: 100%;
  margin: auto;
  padding: 80px 0 100px;
}
.cart-body .cart-empty .message {
  height: 98px;
  background: url(../../public/car.png) no-repeat;
  /* 背景图大小 */
  background-size: contain;
  background-position: 330px;
  padding-left: 445px;
}
.cart-body .cart-empty ul {
  list-style: none;
  padding-top: 20px;
}
.cart-body .cart-empty ul li:first-child {
  font-size: 18px;
}
.cart-body .cart-empty ul li a {
  text-decoration: none;
  color: #ffa500;
  font-size: 15px;
}

/* 推荐 */
.container .recommend {
  margin: auto;
}

/* 猜你喜欢 */
/* 下划线 */
::v-deep .el-tabs__active-bar.is-top {
  background-color: #ffa500;
}

/* 修改活动文字颜色 */
::v-deep .el-tabs__item.is-active {
  color: #ffa500;
  opacity: 1;
}

/* 设置未选中标签的样式 */
::v-deep .el-tabs__item {
  color: #000;
}

/* 设置鼠标悬停未选中标签的样式 */
::v-deep .el-tabs__item:hover {
  color: #ffa500;
  cursor: pointer;
  opacity: 1;
}

.container .recommend .el-menu-demo {
  padding-left: 50px;
}

.container .recommend .el-menu-demo .el-menu-item {
  width: 100px;
  text-align: center;
}

:deep(.container .el-carousel__container) {
  height: 250px;
}

.container .el-carousel__container div {
  height: 150px;
  background-color: whitesmoke;
  opacity: 0.8;
}

.container .el-carousel__container img {
  float: left;
  width: 150px;
  height: 150px;
}

.container .el-carousel__container .title {
  padding-top: 20px;
}

.container .el-carousel__container .price {
  padding-top: 15px;
}

.container .el-carousel__container a {
  display: block;
  padding-top: 10px;
  text-decoration: none;
  color: #ffa500;
}

/* 在 scoped 中要用 :deep ，左右箭头在 .el-carousel__arrow 中 */
:deep(.el-carousel__arrow) {
  top: 80px !important;
}

:deep(.el-carousel__indicators) {
  display: none;
}
</style>
